package network;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

//回显服务器：客户端发什么，服务器就回应什么
public class UdpEchoServer {
    private DatagramSocket socket = null;

    public UdpEchoServer(int port) throws SocketException {
        socket = new DatagramSocket(port);
    }
    public void start() throws IOException {
        System.out.println("服务器启动");
        while (true){
            //反复长期等待用户发请求
            //一个服务器有三个核心:读取，计算，返回
            //1.读取
            DatagramPacket requestPacket = new DatagramPacket(new byte[4096],4096);
            socket.receive(requestPacket);
            //这样子转字符串的前提是客户端发的就是一个字符串

            String request = new String(requestPacket.getData(),0,requestPacket.getLength());
                   //2.请求
            //如果此时客户端请求还没来，receive方法就会阻塞等待

            String response = process(request);
                   //3.响应
            //此时需要告诉网卡，要发的内容是什么，要发给谁
            DatagramPacket responsePacket = new DatagramPacket(response.getBytes(),response.getBytes().length,
                    requestPacket.getSocketAddress());
            socket.send(responsePacket);
            System.out.println();
            //DatagramPacket这个对象包含通信双方的ip和port
            System.out.printf("[%s:%d] req: %s,resp: %s\n",requestPacket.getAddress().toString(),
                    requestPacket.getPort(),request,response);
        }
    }

    public String process(String request){
        return request;
    }

    public static void main(String[] args) throws IOException {
        UdpEchoServer server = new UdpEchoServer(9090);
        server.start();
    }
}
